package com.greyu.ysj.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.web.filter.ShallowEtagHeaderFilter;

import com.google.common.util.concurrent.Service;
import com.greyu.ysj.config.Constants;

import sun.misc.BASE64Encoder;


public class FileTemplateUtils {
	
	/**
	 * 对下载文件的名称进行url编码，防止中文乱码
	 * 
	 * @param filename
	 * @param agent
	 * @return
	 * @throws IOException
	 */
	public static String encodeDownloadFilename(String filename, String agent)
			throws IOException {
		if (agent.contains("Firefox")) { // 火狐浏览器
			filename = "=?UTF-8?B?"
					+ new BASE64Encoder().encode(filename.getBytes("utf-8"))
					+ "?=";
		} else { // IE及其他浏览器
			filename = URLEncoder.encode(filename, "utf-8");
		}
		return filename;
	}
	
	public static void downloanFromExcelTemplate(String templateExcelName, String newName, HttpServletRequest request, HttpServletResponse response) {
		try {
			
			String path = Constants.FILE_PATH;//request.getSession().getServletContext().getRealPath("/");
			String fileName = request.getParameter("fileName");
			path += fileName;
			OutputStream fileOut = response.getOutputStream();
			File file = new File(path);
			response.reset(); 
			response.setHeader("content-disposition", "attachment;fileName=" + fileName);// 对中文名称进行URL编码，针对火狐和其他浏览器有不同的处理方式
			response.setContentType("multipart/form-data");		
			response.setHeader("Content-Length", String.valueOf(file.length()));
			System.out.println(file.length());
			InputStream ips = new FileInputStream(file);
			IOUtils.copy(ips, fileOut);
			IOUtils.closeQuietly(ips);
		} catch (Exception e) {
			//throw new TarringException("模板下载异常", e);
			e.printStackTrace();
		}

	}
}
